package com.yuerenjf.yuerenjinfu.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.PtrHandler;
import com.qiniu.android.utils.StringUtils;
import com.yuerenjf.yuerenjinfu.R;
import com.yuerenjf.yuerenjinfu.activity.LoginActivity;
import com.yuerenjf.yuerenjinfu.activity.MainActivity;
import com.yuerenjf.yuerenjinfu.activity.SettingActivity;
import com.yuerenjf.yuerenjinfu.activity.WebActivity;
import com.yuerenjf.yuerenjinfu.adapter.AdapterOwnSecond;
import com.yuerenjf.yuerenjinfu.adapter.AdapterOwnZiChan;
import com.yuerenjf.yuerenjinfu.bean.BaseOwnInfoBean;
import com.yuerenjf.yuerenjinfu.bean.OwnZichanBean;
import com.yuerenjf.yuerenjinfu.customview.BadgeView;
import com.yuerenjf.yuerenjinfu.customview.ExpandGridView;
import com.yuerenjf.yuerenjinfu.customview.MyPtrClassicFrameLayout;
import com.yuerenjf.yuerenjinfu.http.Constants;
import com.yuerenjf.yuerenjinfu.http.Xutils;
import com.yuerenjf.yuerenjinfu.utils.CacheUtils;
import com.yuerenjf.yuerenjinfu.utils.ConstantUtils;

import org.xutils.common.util.LogUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/6/13.
 */
public class FragmentOwn extends BaseFragment implements View.OnClickListener {
    MyPtrClassicFrameLayout myPtrClassicFrameLayout;
    ScrollView mScrollView;
    private LinearLayout mFragment_own_money_layout;
    private TextView mMessageNumText;
    private FrameLayout mMessageFrameLayout;
    BadgeView badgeView;

    private TextView mFragment_money_text;
    private TextView mLl_user_recharge;
    private TextView mLl_user_invest;
    private TextView mFragment_own_tatal_money_text;
    private ExpandGridView mFragment_own_zichan_gridview;
    private ExpandGridView mFragment_own_second_gridview;
    private ExpandGridView mFragment_own_third_gridview;

    boolean isFirst=true;
    @Override
    public void prepareData() {

    }


    @Override
    public View prepareView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fragment_own, null);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if(!isFirst){
            getDataForRemote();
        }


    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        LogUtil.i("OwnHome_onActivityCreated");
        MainActivity mainActivity = (MainActivity) getActivity();
        mainActivity.setmTitleTextView("个人中心");
        mainActivity.setLogoImageShow(false);

//        getDataForRemote();
    }

    private void setTopGridViewData(final List<OwnZichanBean> beanList) {
        AdapterOwnZiChan topAdapter = new AdapterOwnZiChan(getActivity(), beanList);
        mFragment_own_zichan_gridview.setAdapter(topAdapter);
        mFragment_own_zichan_gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                WebActivity.launchActivity(getActivity(),beanList.get(i).getWebUrl());
            }
        });
    }


    private void setSecondListView(final List<OwnZichanBean> beanList) {
        AdapterOwnSecond topAdapter = new AdapterOwnSecond(getActivity(), beanList);
        mFragment_own_second_gridview.setAdapter(topAdapter);
        mFragment_own_second_gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                WebActivity.launchActivity(getActivity(),beanList.get(i).getWebUrl());
            }
        });
    }


    private void setmTogetherExpandGridViewData(final List<OwnZichanBean> beanList) {
        AdapterOwnSecond topAdapter = new AdapterOwnSecond(getActivity(), beanList);
        mFragment_own_third_gridview.setAdapter(topAdapter);
        mFragment_own_third_gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                WebActivity.launchActivity(getActivity(),beanList.get(i).getWebUrl());
            }
        });
    }


    @Override
    public void onloadData(View view) {
        myPtrClassicFrameLayout = (MyPtrClassicFrameLayout) view.findViewById(R.id.MyPtrClassicFrameLayout);
        mScrollView = (ScrollView) view.findViewById(R.id.own_scrollview);
        mFragment_own_money_layout = (LinearLayout) view.findViewById(R.id.fragment_own_money_layout);
        mFragment_money_text = (TextView) view.findViewById(R.id.fragment_money_text);
        mLl_user_recharge = (TextView) view.findViewById(R.id.ll_user_recharge);
        mLl_user_invest = (TextView) view.findViewById(R.id.ll_user_invest);
        mFragment_own_tatal_money_text = (TextView) view.findViewById(R.id.fragment_own_tatal_money_text);
        mFragment_own_zichan_gridview = (com.yuerenjf.yuerenjinfu.customview.ExpandGridView) view.findViewById(R.id.fragment_own_zichan_gridview);
        mFragment_own_second_gridview = (com.yuerenjf.yuerenjinfu.customview.ExpandGridView) view.findViewById(R.id.fragment_own_second_gridview);
        mFragment_own_third_gridview = (com.yuerenjf.yuerenjinfu.customview.ExpandGridView) view.findViewById(R.id.fragment_own_third_gridview);

        view.findViewById(R.id.own_setting_text).setOnClickListener(this);
        mMessageNumText = (TextView) view.findViewById(R.id.own_message_text);
        mMessageFrameLayout = (FrameLayout) view.findViewById(R.id.own_message_framelayout);


        myPtrClassicFrameLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                myPtrClassicFrameLayout.autoRefresh(true);
            }
        }, 150);
        myPtrClassicFrameLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, mScrollView, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                myPtrClassicFrameLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getDataForRemote();

                    }
                }, 100);
            }
        });


    }

    @Override
    public void adapterScreen() {

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);

    }

    @Override
    public void onStop() {
        super.onStop();
        LogUtil.i("onStop");
    }

    @Override
    public void resume() {
        super.resume();
        LogUtil.i("resume");
        if(getActivity()!=null) {
            String uid = CacheUtils.getString(getActivity(), ConstantUtils.SP_UID);
            if (StringUtils.isNullOrEmpty(uid)) {
                LoginActivity.launchLoginActivity(getActivity(), LoginActivity.FROM_TYPE_MAIN_TAB);
            }
        }
        //开始查询
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.own_setting_text://设置界面
                SettingActivity.launchActivity(getActivity());
                break;
        }
    }


    private void getDataForRemote() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("signature", CacheUtils.getString(getActivity(), ConstantUtils.SP_SIGNATURE));
        map.put("uid", CacheUtils.getString(getActivity(), ConstantUtils.SP_UID));
        Xutils.getInstance().post(getActivity(), Constants.URL_OWN, map, new Xutils.XCallBack() {
            @Override
            public void onResponse(String result) {
                myPtrClassicFrameLayout.refreshComplete();

                final BaseOwnInfoBean baseOwnInfoBean = gson.fromJson(result, BaseOwnInfoBean.class);

                final BaseOwnInfoBean.DataBean dataBean = baseOwnInfoBean.getData();
                BaseOwnInfoBean.DataBean.UserListBean userListBeans = dataBean.getUser_list();


                mFragment_money_text.setText(dataBean.getMoney_real());
                mFragment_own_tatal_money_text.setText(dataBean.getAccount_total());

                //预计出借收益
                List<OwnZichanBean> topGridDatas = new ArrayList<>();
                List<BaseOwnInfoBean.DataBean.UserListBean.TotalMoneyBean> interestBeans = userListBeans.getTotal_money();
                if(interestBeans!=null){
                    for (int i = 0; i < interestBeans.size(); i++) {
                        OwnZichanBean shouyiBean = new OwnZichanBean();
                        BaseOwnInfoBean.DataBean.UserListBean.TotalMoneyBean b = interestBeans.get(i);
                        shouyiBean.setText(b.getTotal_interest_name());
                        shouyiBean.setImage(b.getTotal_interest_image());
                        shouyiBean.setMoney(b.getTotal_interest_money());
                        shouyiBean.setWebUrl(b.getTotal_interest_url());
                        topGridDatas.add(shouyiBean);
                    }
                    if(interestBeans.size()%2==1){
                        topGridDatas.add(new OwnZichanBean());
                    }
                }


                setTopGridViewData(topGridDatas);


                List<OwnZichanBean> secondGridDatas = new ArrayList<>();
                List<BaseOwnInfoBean.DataBean.UserListBean.AccountDebtrightBean> accountDebtrightBeans = userListBeans.getAccount_debtright();
                if(null!=accountDebtrightBeans) {
                    for (int i = 0; i < accountDebtrightBeans.size(); i++) {
                        OwnZichanBean shouyiBean = new OwnZichanBean();
                        BaseOwnInfoBean.DataBean.UserListBean.AccountDebtrightBean b = accountDebtrightBeans.get(i);
                        shouyiBean.setText(b.getAccount_logs_name());
                        shouyiBean.setImage(b.getAccount_logs_image());
                        shouyiBean.setWebUrl(b.getAccount_logs_url());
                        if (b.getAccount_logs_name().equals("优惠券")) {
                            shouyiBean.setNumber("有" + b.getCards_nums() + "张可用");
                        }
                        secondGridDatas.add(shouyiBean);
                    }
                    if(accountDebtrightBeans.size()%2==1){
                        secondGridDatas.add(new OwnZichanBean());
                    }
                }
                setSecondListView(secondGridDatas);


                List<OwnZichanBean> thirdGridDatas = new ArrayList<>();
                List<BaseOwnInfoBean.DataBean.UserListBean.LoadRepaymentBean> mLoadRepaymentBean = userListBeans.getLoad_repayment();
                if(null!=mLoadRepaymentBean){
                    for (int i = 0; i < mLoadRepaymentBean.size(); i++) {
                        OwnZichanBean shouyiBean = new OwnZichanBean();
                        BaseOwnInfoBean.DataBean.UserListBean.LoadRepaymentBean b = mLoadRepaymentBean.get(i);
                        shouyiBean.setText(b.getAccount_logs_name());
                        shouyiBean.setImage(b.getAccount_logs_image());
                        shouyiBean.setWebUrl(b.getAccount_logs_url());
                        thirdGridDatas.add(shouyiBean);
                    }
                    if(mLoadRepaymentBean.size()%2==1){
                        thirdGridDatas.add(new OwnZichanBean());
                    }
                }

                setmTogetherExpandGridViewData(thirdGridDatas);

                //充值
                mLl_user_recharge.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LogUtil.i(dataBean.getRecharge_url());
                        WebActivity.launchActivity(getActivity(),dataBean.getRecharge_url());
                    }
                });

                //提现
                mLl_user_invest.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LogUtil.i(dataBean.getCash_url());
                        WebActivity.launchActivity(getActivity(),dataBean.getCash_url());
                    }
                });

                //消息
                mMessageFrameLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        WebActivity.launchActivity(getActivity(),dataBean.getMessage_url());
                    }
                });

                int count=0;
                try{
                    count=  Integer.valueOf(dataBean.getMessage());
                }catch (Exception e){
                    e.printStackTrace();
                    count=0;
                }
                if(count<99&&count>0){
                    BadgeView badgeView = new BadgeView(getActivity());
                    badgeView.setTargetView(mMessageFrameLayout);
                    badgeView.setBadgeCount(count);
                }else if(count>99){
                    BadgeView badgeView = new BadgeView(getActivity());
                    badgeView.setTargetView(mMessageFrameLayout);
                    badgeView.setText("99+");
                }


            }

            @Override
            public void onFailer(int status, String result) {

            }

            @Override
            public void onFinish() {
                myPtrClassicFrameLayout.refreshComplete();
                isFirst=false;
            }
        });

    }

}